# -*- coding: utf-8 -*

import math
from PIL import Image

def encoding_images(img, msg):

    index = 0
    encoded = img.copy()
    width, height = img.size
    length = len(msg)
    if img:
        h,s,v = int(identify_mode(img))
        for hi in range(h):
            for si in range(s):
                for vi in range(v):
                    if hi == 0 and si == 0 and vi == 0 and index < length:
                        Hiasc = length
                    elif index <= length:
                        c = msg[index -1]
                        Hiasc = ord(c)
                    else:
                        Hiasc = h
                    r,g,b = hsv2rgb(Hiasc,si,vi)
                    index += 1

    for row in range(height):
        for col in range(width):
            encoded.putpixel((col, row), (r, g , b))
    return encoded


def identify_mode(img):
    width,height = img.size
    for row in range(height):
        for col in range(width):
            r, g, b = img.getpixel((col, row))
            h,s,v = rgb2hsv(r,g,b)
    return h,s,v
	


def hsv2rgb(h, s, v):
    h = float(h)
    s = float(s)
    v = float(v)
    h60 = h / 60.0
    h60f = math.floor(h60)
    hi = int(h60f) % 6
    f = h60 - h60f
    p = v * (1 - s)
    q = v * (1 - f * s)
    t = v * (1 - (1 - f) * s)
    r, g, b = 0, 0, 0
    if hi == 0: r, g, b = v, t, p
    elif hi == 1: r, g, b = q, v, p
    elif hi == 2: r, g, b = p, v, t
    elif hi == 3: r, g, b = p, q, v
    elif hi == 4: r, g, b = t, p, v
    elif hi == 5: r, g, b = v, p, q
    r, g, b = int(r * 255), int(g * 255), int(b * 255)
    return r, g, b

def rgb2hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    return h, s, v



image_file = "Bitmap.bmp"

img = Image.open(image_file)

print("\n ͼ�����ͣ�"+str(img))
print("\n ͼ��ɫ��ϵ��"+str(img.mode))


# �����ļ���
encoded_image_file = "enceded_" + image_file

# ��д���ı���Ϣ
msg = "this is a secret message-------------Hello,everyone.I am a student ,our university is South West University Of Scince And Technology.welcome to here study.610001,China,SiChuan ,MianYang,610001.this is our Steganography class assignment."
print("\n�ַ�����Ϣ����Ϊ��"+str(len(msg)))

img_encoded = encoding_images(img,msg)

if img_encoded:
    # ������д���ͼƬ
    img_encoded.save(encoded_image_file)
    print("{} ��дͼƬ�ѱ���!".format(encoded_image_file))

    
    # ���������ģ�飬����д���ͼƬ
    import webbrowser
    webbrowser.open(encoded_image_file)
